package com.weixin.paleituo.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;

import com.weixin.paleituo.R;
import com.weixin.paleituo.adapter.OrderShippingAddressRecycleAdapter;
import com.weixin.paleituo.adapter.ShippingAddressRecycleAdapter;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.BasePersonActivity;
import com.weixin.paleituo.bean.ShippingAddressBean;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.eventbus.CheckDeleteAddressEvent;
import com.weixin.paleituo.eventbus.CheckSetDefaultAddressEvent;
import com.weixin.paleituo.eventbus.CheckUpdateAddressEvent;
import com.weixin.paleituo.eventbus.CheckUpdateOrderAddressEvent;
import com.weixin.paleituo.eventbus.OrderChooseAddressEvent;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.LoadingPagerHead;
import com.weixin.paleituo.view.ShopCarToastView;
import com.weixin.paleituo.view.TipsDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;

/**
 * 购物车地址管理界面
 * 两种类型：
 * 从“地址管理”进入：{@link ManagerAddressActivity {@link #TYPE_FROM_USER}},
 * 展示可删除、可修改item类型,同时可以设置默认地址。item点击无效果
 * 从“创建订单”进入：{@link ManagerAddressActivity {@link #TYPE_FROM_ORDER}},
 * 展示仅可修改、无删除地址item类型，无法更改默认地址。item点击即为选定改地址，返回数据
 *
 * @author fengzhen
 * @version v1.0, 2018/3/27
 */
public class ManagerAddressActivity extends BasePersonActivity {

    public static final int REQUEST_ADD = 0x12;
    public static final int REQUEST_UPDATE = 0x13;

    public static final int TYPE_FROM_USER = 0x889;
    public static final int TYPE_FROM_ORDER = 0x888;

    public static final String ARGS_TYPE = "args_type";
    public static final String ARGS_ID = "args_id";

    @BindView(R.id.recycle_activity_manager_address)
    RecyclerView mRecycleActivityManagerAddress;

    private LoadingPagerHead mLoadingPager;

    private List<ShippingAddressBean> mAddressList = new ArrayList<>();
    private ShippingAddressRecycleAdapter mAddressAdapter;
    private OrderShippingAddressRecycleAdapter mOrderAddressAdapter;
    private TipsDialog mCancelTipsDialog;

    private int mType = TYPE_FROM_USER;
    private int mChooseId = -1;

    /**
     * 跳转地址管理界面
     *
     * @param chooseId 被选择中的id  默认传 -1
     * @author fengzhen
     * @version v1.0, 2018/3/28
     */
    public static Intent call2AddressManagerActivity(Context context, int type, int chooseId) {
        Intent intent = new Intent(context, ManagerAddressActivity.class);
        intent.putExtra(ARGS_TYPE, type);
        intent.putExtra(ARGS_ID, chooseId);
        return intent;
    }

    @Override
    protected View getContentView(Context context) {
        mLoadingPager = new LoadingPagerHead(this, R.layout.activity_manager_address_empty) {
            @Override
            protected void close() {
            }

            @Override
            protected View createSuccessView() {
                return UIUtils.inflate(ManagerAddressActivity.this, R.layout.activity_manager_address);
            }

            @Override
            protected void reLoading() {
                getShippingAddress();
            }
        };
        return mLoadingPager;
    }

    @Override
    protected void initData() {
        super.initData();
        EventBus.getDefault().register(this);

        mType = getIntent().getIntExtra(ARGS_TYPE, TYPE_FROM_ORDER);
        mChooseId = getIntent().getIntExtra(ARGS_ID, -1);

        if (mType == TYPE_FROM_USER) {
            mTvTitle.setText("地址管理");
            mAddressAdapter = new ShippingAddressRecycleAdapter(this, mAddressList);
            mRecycleActivityManagerAddress.setAdapter(mAddressAdapter);
        } else if (mType == TYPE_FROM_ORDER) {
            mTvTitle.setText("收货地址");
            mOrderAddressAdapter = new OrderShippingAddressRecycleAdapter(this, mAddressList, mChooseId);
            mRecycleActivityManagerAddress.setAdapter(mOrderAddressAdapter);
            mRecycleActivityManagerAddress.addItemDecoration(new RecyclerView.ItemDecoration() {
                @Override
                public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                    // 对Item进行偏移
                    outRect.set(0, 0, 0, UIUtils.dip2px(1));
                }
            });
        }

        // 处理列表数据
        mRecycleActivityManagerAddress.setLayoutManager(
                new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mRecycleActivityManagerAddress.setItemAnimator(new DefaultItemAnimator());

        getShippingAddress();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_ADD:
                case REQUEST_UPDATE:
                    if (mType == TYPE_FROM_ORDER) {
                        Intent intent = new Intent();
                        intent.putExtra(Contans.INTENT_DATA, data.getParcelableExtra(Contans.INTENT_DATA));
                        setResult(RESULT_OK, intent);
                        finish();
                    } else {
                        refreshShippingAddress();
                    }
                    break;
            }
        }
    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_CANCELED);
        super.onBackPressed();
    }

    @OnClick({R.id.linear_add_address_activity_manager_address,
            R.id.linear_add_address_activity_manager_address_empty,
            R.id.iv_back_activity_basepersoninfo})
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.iv_back_activity_basepersoninfo:
                onBackPressed();
                break;

            /**
             *  跳转新增地址
             *
             * @author fengzhen
             * @version v1.0, 2018/3/28
             */
            case R.id.linear_add_address_activity_manager_address:
            case R.id.linear_add_address_activity_manager_address_empty:
                if (mType == TYPE_FROM_USER) {
                    startActivityForResult(
                            NewShippingAddressActivity.call2NewShippingAddressActivity(this, NewShippingAddressActivity.TYPE_NEW),
                            REQUEST_ADD);
                } else if (mType == TYPE_FROM_ORDER) {
                    startActivityForResult(
                            NewShippingAddressActivity.call2NewShippingAddressActivity(this, NewShippingAddressActivity.TYPE_NEW_USE),
                            REQUEST_ADD);
                }
                break;
        }
    }

    /**
     * 获取物流配送地址列表
     *
     * @author fengzhen
     * @version v1.0, 2018/3/27
     */
    private void getShippingAddress() {

        mLoadingPager.showPagerView(Contans.STATE_LOADING);

        Observable<StatusCode<List<ShippingAddressBean>>> shippingAddressObservable = ApiUtils.getApi().getShippingAddress(
                BaseApplication.getToken(), BaseApplication.getUserId()
        );
        HttpUtil.getInstance().toSubscribe(shippingAddressObservable,
                new ProgressSubscriber<List<ShippingAddressBean>>(this) {
                    @Override
                    protected void _onNext(StatusCode<List<ShippingAddressBean>> listStatusCode) {
                        List<ShippingAddressBean> data = listStatusCode.getData();
                        if (data == null || data.size() <= 0) {
                            mLoadingPager.showPagerView(Contans.STATE_EMPTY);
                        } else {
                            mLoadingPager.showPagerView(Contans.STATE_SUCCEED);
                            mAddressList.clear();
                            mAddressList.addAll(data);
                            if (mAddressAdapter != null) {
                                mAddressAdapter.notifyDataSetChanged();
                            }
                            if (mOrderAddressAdapter != null) {
                                mOrderAddressAdapter.notifyDataSetChanged();
                            }
                        }
                    }

                    @Override
                    protected void _onError(String message) {
                        mLoadingPager.showPagerView(Contans.STATE_ERROR);
                    }
                }, "", lifecycleSubject, false, true);
    }

    /**
     * 刷新物流配送地址列表
     *
     * @author fengzhen
     * @version v1.0, 2018/3/27
     */
    private void refreshShippingAddress() {
        Observable<StatusCode<List<ShippingAddressBean>>> shippingAddressObservable = ApiUtils.getApi().getShippingAddress(
                BaseApplication.getToken(), BaseApplication.getUserId()
        );
        HttpUtil.getInstance().toSubscribe(shippingAddressObservable,
                new ProgressSubscriber<List<ShippingAddressBean>>(this) {
                    @Override
                    protected void _onNext(StatusCode<List<ShippingAddressBean>> listStatusCode) {
                        dismissLoadingDialog();
                        List<ShippingAddressBean> data = listStatusCode.getData();
                        if (data == null || data.size() <= 0) {
                            mLoadingPager.showPagerView(Contans.STATE_EMPTY);
                        } else {
                            mLoadingPager.showPagerView(Contans.STATE_SUCCEED);
                            mAddressList.clear();
                            mAddressList.addAll(data);
                            if (mAddressAdapter != null) {
                                mAddressAdapter.notifyDataSetChanged();
                            }
                            if (mOrderAddressAdapter != null) {
                                mOrderAddressAdapter.notifyDataSetChanged();
                            }
                        }
                    }

                    @Override
                    protected void _onError(String message) {
                        dismissLoadingDialog();
                    }
                }, "", lifecycleSubject, false, true);
    }

    /**
     * 删除物流地址信息
     *
     * @param id 删除地址id
     * @author fengzhen
     * @version v1.0, 2018/3/29
     */
    private void deleteAddress(int id) {
        showLoadingDialog();
        Observable<StatusCode<String>> deleteAddressObservable = ApiUtils.getApi().deleteShippingAddress(
                BaseApplication.getToken(),
                BaseApplication.getUserId(),
                id);
        HttpUtil.getInstance().toSubscribe(deleteAddressObservable,
                new ProgressSubscriber(this) {
                    @Override
                    protected void _onNext(StatusCode statusCode) {
                        refreshShippingAddress();
                    }

                    @Override
                    protected void _onError(String message) {
                        dismissLoadingDialog();
                    }
                }, "", lifecycleSubject, false, true);
    }

    /**
     * 处理点击设置默认地址
     *
     * @author fengzhen
     * @version v1.0, 2018/3/29
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setDefaultAddress(CheckSetDefaultAddressEvent event) {

        showLoadingDialog();
        Observable<StatusCode<String>> defaultAddObservable = ApiUtils.getApi().setDefaultAddress(BaseApplication.getToken(),
                BaseApplication.getUserId(),
                2,
                event.getId());
        HttpUtil.getInstance().toSubscribe(defaultAddObservable, new ProgressSubscriber(this) {
            @Override
            protected void _onNext(StatusCode statusCode) {
                ShopCarToastView shopCarToastView= new ShopCarToastView(ManagerAddressActivity.this);
                shopCarToastView.setIcon(R.mipmap.address_success);
                shopCarToastView.setText("设置成功");
                shopCarToastView.setDuration(Toast.LENGTH_LONG);
                shopCarToastView.show();

                refreshShippingAddress();
            }

            @Override
            protected void _onError(String message) {
                dismissLoadingDialog();
            }
        }, "", lifecycleSubject, false, true);
    }

    /**
     * 处理点击编辑地址
     *
     * @author fengzhen
     * @version v1.0, 2018/3/29
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateAddress(CheckUpdateAddressEvent event) {
        startActivityForResult(NewShippingAddressActivity.call2NewShippingAddressActivity(
                this, NewShippingAddressActivity.TYPE_UPDATE, event.getAdd()
        ), REQUEST_UPDATE);
    }

    /**
     * 处理点击编辑地址 订单入口
     *
     * @author fengzhen
     * @version v1.0, 2018/3/29
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateAddressOrder(CheckUpdateOrderAddressEvent event) {
        startActivityForResult(NewShippingAddressActivity.call2NewShippingAddressActivity(
                this, NewShippingAddressActivity.TYPE_UPDATE_USE, event.getAdd()
        ), REQUEST_UPDATE);
    }

    /**
     * 选择该订单地址
     *
     * @author fengzhen
     * @version v1.0, 2018/3/29
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void selectAddress(OrderChooseAddressEvent event) {
        Intent intent = new Intent();
        intent.putExtra(Contans.INTENT_DATA, event.getAdd());
        setResult(RESULT_OK, intent);
        finish();
    }

    /**
     * 处理点击删除地址
     *
     * @author fengzhen
     * @version v1.0, 2018/3/29
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void deleteAddressTips(final CheckDeleteAddressEvent event) {
        if (mCancelTipsDialog == null) {
            mCancelTipsDialog = new TipsDialog.Builder(this)
                    .setCancelClickListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            mCancelTipsDialog.dismiss();
                        }
                    })
                    .setContentView("是否确定删除该地址？")
                    .setLeftButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mCancelTipsDialog.dismiss();
                        }
                    })
                    .setRightButton("确定", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mCancelTipsDialog.dismiss();
                            deleteAddress((int) mCancelTipsDialog.getTag());
                        }
                    })
                    .build();
        }
        // 设置Dialog对象，解决错位问题
        mCancelTipsDialog.setTag(event.getId());
        mCancelTipsDialog.show();
    }
}
